from bs4 import BeautifulSoup
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
import re

import config
import requests

url = rf'https://card.whutech.com/balance/hgh/{config.card_num}.html'


# -------- 估算列宽（考虑中文字符） --------
def excel_width(text):
    count = 0
    for ch in str(text):
        count += 2 if ord(ch) > 127 else 1
    return count


if __name__ == '__main__':
    response = requests.get(url)
    
    soup = BeautifulSoup(response.text, "html.parser")
    rows = soup.select("div.weui-cell")[1:]  # 跳过表头
    
    wb = Workbook()
    ws = wb.active
    ws.title = "交易记录"
    
    headers = ["日期", "类型", "金额（元）"]
    ws.append(headers)
    column_widths = [excel_width(h) for h in headers]
    
    # -------- 提取并写入数据 --------
    for row in rows:
        cols = row.select("div")
        if len(cols) < 3:
            continue
        
        date_str = cols[0].text.strip()
        type_str = cols[1].text.strip()
        amount_text = cols[2].text.strip()
        
        match = re.search(r"([\d.]+)", amount_text)
        if not match:
            continue
        amount = float(match.group(1))
        
        values = [date_str, type_str, amount]
        ws.append(values)
        
        for i, val in enumerate(values):
            column_widths[i] = max(column_widths[i], excel_width(val))
    
    # -------- 设置列宽 --------
    for i, width in enumerate(column_widths, 1):
        col_letter = get_column_letter(i)
        ws.column_dimensions[col_letter].width = (width + 2) * 0.9  # 略微收紧避免太宽
    
    # -------- 设置首行筛选器 --------
    ws.auto_filter.ref = "A1:C1"
    
    # -------- 保存文件 --------
    output_file = "杭州通明细.xlsx"
    wb.save(output_file)
    print(f"✅ 已保存为 {output_file}（中文列宽已优化）")
